package xyz.luxiaoxiang.thread;

import java.io.File;
import java.util.concurrent.*;

/**
 * 假如有Thread1、Thread2、ThreaD3、Thread4四条线程分别统计C、D、E、F四个盘的大小，
 * 所有线程都统计完毕交给Thread5线程去做汇总，应当如何实现？
 *
 * @author luxx
 */
public class CallableThreadTest {

    public static void main(String[] args) {

        ExecutorService executorService = Executors.newCachedThreadPool();
        CompletionService<Long> completionService = new ExecutorCompletionService<>(executorService);

        //创建4条线程
        completionService.submit(new ThreadTest("c"));
        completionService.submit(new ThreadTest("d"));
        completionService.submit(new ThreadTest("e"));
        completionService.submit(new ThreadTest("f"));

        // 添加结束，及时shutdown，不然主线程不会结束
        executorService.shutdown();

        int total = 0;
        for (int i = 0; i < 4; i++) {
            try {
                total += completionService.take().get();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
        }

        System.out.println("磁盘总容量为:" + total + "G");
    }
}

class ThreadTest implements Callable<Long> {
    private String spaceName;

    ThreadTest(String spaceName) {
        this.spaceName = spaceName;
    }

    @Override
    public Long call() throws Exception {
        return getTotalSpace(spaceName);
    }

    public static Long getTotalSpace(String SpaceName) {
        File file = new File(SpaceName + ":");
        long size = file.getTotalSpace() / 1024 / 1024 / 1024;
        System.out.println(SpaceName + "的大小:" + size + "G");
        return size;
    }
}